﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.Content;
using MethodWorx.CMS.Services;
using MethodWorx.CMS.Plugins;

namespace MethodWorx.CMS.Workflow.SetContentItemProperty
{
    public class SetContentItemPropertyWorkflowComponent : WorkflowComponent<SetContentItemPropertyConfigurationController>
    {
        public SetContentItemPropertyWorkflowComponent(Plugin plugin)
            : base(plugin)
        {
        }

        public static Guid ComponentId = Guid.Parse("{68347D1C-4557-4490-A38A-9484D62299D9}");

        public override Guid Id
        {
            get { return ComponentId;  }
        }

        public override string Category
        {
            get { return "Content";  }
        }

        public override string Name
        {
            get { return "Set Content Item Property";  }
        }

        public override string Description
        {
            get { return "Allows a content item property to be set";  }
        }

        public override string View
        {
            get { return "SetContentItemPropertyConfigurationView.ascx"; }
        }

        public override StepExecutionResult Execute(IWorkflowExecutionContext context, IWorkflowConfiguration configuration)
        {
            //
            //  ok, here we go..
            var currentPage = context.GetWorkflowValue("currentPage") as Page;
            var config = configuration as SetContentItemPropertyConfiguration;

            if (currentPage != null && config != null)
            {
                //  ok find the item in the context first
                var contentItem = context.GetWorkflowValue(config.ContentItem.TrimStart('{').TrimEnd('}')) as ContentItem;
                //  then look in the current page
                if (contentItem == null)
                    contentItem = currentPage.ChildContent.FirstOrDefault(c => c.Name.ToLower() == this.ParseString(config.ContentItem, context.GetAllWorkflowValues()).ToLower());

                if (contentItem == null)
                    return StepExecutionResult.Error("Content Item Not Found");

                //
                // set the content item property
                var properties = (contentItem.Properties ?? new PageProperty[] { }).ToList();
                var property = properties.FirstOrDefault(p => p.Name.ToLower() == config.Property.ToLower());
                if (property == null)
                {
                    var templateProperty = contentItem.Template.Properties.FirstOrDefault(p => p.Name.ToLower() == config.Property.ToLower());
                    if (templateProperty == null)
                        return StepExecutionResult.Error("Property not found");

                    property = new PageProperty()
                    {
                        Name = templateProperty.Name,
                        Value = templateProperty.Custom
                    };

                    properties.Add(property);
                }


                //
                //  ok, we have a property, so lets parse
                property.Value.Parse(this.ParseString(config.Value, context.GetAllWorkflowValues()));
                //  update the properties
                new ContentService(context.CmsDataProvider)
                    .UpdateContentItemProperties(contentItem.Id, GetPropertyDictionary(properties));

                    

                return StepExecutionResult.Ok();
            }
            else
                return StepExecutionResult.Error("Unexpected error, invalid configuration");
        }

        private Dictionary<string, ICustomPropertyDetails> GetPropertyDictionary(IList<PageProperty> properties)
        {
            var dict = new Dictionary<string, ICustomPropertyDetails>();
            foreach (var item in properties)
            {
                dict.Add(item.Name, item.Value);
            }
            return dict;
        }
    }


}
